<template>
  <a-modal
    title="扫描日志"
    :visible="logModalVisible"
    @cancel="logModalVisible = false"
    width="700px"
    :footer="null"
  >
    <div class="log-modal-content">
      <div class="log-actions-bar">
        <a-button-group>
          <a-button type="primary" size="small" @click="clearLog">
            <a-icon type="delete" /> 清空日志
          </a-button>
          <a-button type="primary" size="small" @click="copyLog">
            <a-icon type="copy" /> 复制日志
          </a-button>
          <a-button type="primary" size="small" @click="exportLog">
            <a-icon type="download" /> 导出日志
          </a-button>
        </a-button-group>
      </div>
      <div class="log-timeline-container">
        <a-timeline v-if="logEntries.length > 0">
          <a-timeline-item
            v-for="(entry, index) in logEntries"
            :key="index"
            :color="getLogColor(entry.type)"
          >
            <span class="log-time">{{ entry.time }}</span>
            <span :class="['log-message', entry.type]">{{
              entry.message
            }}</span>
          </a-timeline-item>
        </a-timeline>
        <div v-else class="empty-log">
          <a-empty description="暂无日志记录" />
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';

@Component
export default class LoggingComponent extends Vue {
  // 属性
  @Prop({ default: false }) visible!: boolean;

  // 数据
  logModalVisible = false;
  logEntries: Array<{
    time: string;
    type: 'info' | 'warning' | 'error' | 'success';
    message: string;
  }> = [];

  // 计算属性
  get logText(): string {
    return this.logEntries
      .map((entry) => `[${entry.time}][${entry.type}] ${entry.message}`)
      .join('\n');
  }

  // 监听器
  @Watch('visible')
  onVisibleChange(val: boolean): void {
    this.logModalVisible = val;
  }

  @Watch('logModalVisible')
  onLogModalVisibleChange(val: boolean): void {
    this.$emit('update:visible', val);
  }
  

  // 生命周期钩子
  mounted(): void {
    // 初始化工作
  }

  // 方法
  /**
   * 添加日志条目
   */
  addLog(
    message: string,
    type: 'info' | 'warning' | 'error' | 'success' = 'info',
  ): void {
    const now = new Date();
    const time = `${now.toLocaleDateString()} ${now.toLocaleTimeString()}`;
    this.logEntries.push({ time, type, message });

    // 如果日志条目过多，可以限制数量
    if (this.logEntries.length > 200) {
      this.logEntries = this.logEntries.slice(-200);
    }

    // 触发事件，通知父组件日志已更新
    this.$emit('log-added', { time, type, message });
  }

  /**
   * 获取日志类型对应的颜色
   */
  getLogColor(type: string): string {
    const colorMap = {
      info: 'blue',
      warning: 'orange',
      error: 'red',
      success: 'green',
    };
    return colorMap[type] || 'blue';
  }

  /**
   * 清空日志
   */
  clearLog(): void {
    this.logEntries = [];
    this.$message.success('日志已清空');
    this.$emit('logs-cleared');
  }

  /**
   * 复制日志到剪贴板
   */
  copyLog(): void {
    const logText = this.logText;

    try {
      // 创建一个临时文本区域元素
      const textArea = document.createElement('textarea');
      textArea.value = logText;

      // 将文本区域添加到文档中
      textArea.style.position = 'fixed';
      textArea.style.left = '-999999px';
      textArea.style.top = '-999999px';
      document.body.appendChild(textArea);

      // 选择并复制文本
      textArea.focus();
      textArea.select();

      const successful = document.execCommand('copy');

      // 删除临时文本区域
      document.body.removeChild(textArea);

      if (successful) {
        this.$message.success('日志已复制到剪贴板');
      } else {
        this.$message.error('复制失败，请手动复制');
      }
    } catch (err) {
      console.error('复制失败:', err);
      this.$message.error('复制失败，请手动复制');
    }
  }

  /**
   * 导出日志到文件
   */
  exportLog(): void {
    const logText = this.logText;
    const blob = new Blob([logText], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `扫描日志_${new Date()
      .toISOString()
      .slice(0, 19)
      .replace(/:/g, '-')}.txt`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    this.$message.success('日志已导出');
  }

  /**
   * 显示日志模态框
   */
  showLogModal(): void {
    this.logModalVisible = true;
    this.$emit('log-modal-shown');
  }

  /**
   * 隐藏日志模态框
   */
  hideLogModal(): void {
    this.logModalVisible = false;
    this.$emit('log-modal-hidden');
  }


}
</script>

<style lang="less" scoped>
.log-modal-content {
  max-height: 70vh;
  display: flex;
  flex-direction: column;
}

.log-actions-bar {
  margin-bottom: 12px;
  display: flex;
  justify-content: flex-end;
}

.log-timeline-container {
  overflow-y: auto;
  max-height: calc(70vh - 50px);
  padding: 12px;
  box-sizing: border-box;
}

.log-time {
  color: #888;
  margin-right: 8px;
  font-size: 12px;
}

.log-message {
  white-space: pre-wrap;
  word-break: break-all;

  &.info {
    color: #1890ff;
  }

  &.warning {
    color: #faad14;
  }

  &.error {
    color: #f5222d;
  }

  &.success {
    color: #52c41a;
  }
}

.empty-log {
  padding: 40px 0;
}
</style>
